<template>
  <div class="kill-section-wrapper">
    <div class="kill-section">
      <div class="kill-header">
        <div class="kill-title">
          <span class="fire-icon">🔥</span>
          <span class="title-text">限时秒杀</span>
        </div>
        <div class="kill-timer" v-if="timeLeft">
          <span class="timer-label">距结束</span>
          <span class="timer-value">{{ timeLeft }}</span>
        </div>
      </div>
        
      <div class="kill-content" v-loading="loading">
        <div class="kill-items" v-if="killItems.length > 0">
          <div 
            class="kill-item" 
            v-for="item in killItems" 
            :key="item.id"
            @click="goToDetail(item.id)"
          >
          <div class="item-image">
            <img :src="item.image" :alt="item.name" />
            <div class="kill-badge">秒杀</div>
          </div>
          <div class="item-info">
            <div class="item-name">{{ item.name }}</div>
            <div class="item-price">
              <span class="kill-price">¥{{ item.killPrice }}</span>
              <span class="original-price">¥{{ item.price }}</span>
            </div>
            <div class="item-stock">
              <span>仅剩{{ item.stock }}件</span>
            </div>
            <el-button 
              type="danger" 
              size="small" 
              class="add-cart-btn"
              @click.stop="handleAddToCart(item)"
              :loading="addingToCart[item.id]"
            >
              立即抢购
            </el-button>
          </div>
        </div>
        </div>
        <div class="empty-state" v-else-if="!loading">
          <span>暂无秒杀商品</span>
        </div>
      </div>
    </div>
  
  <!-- 地址选择对话框 -->
  <el-dialog
    v-model="showAddressDialog"
    title="选择收货地址"
    width="500px"
    :close-on-click-modal="false"
  >
    <div class="address-dialog">
      <div class="kill-item-info" v-if="currentKillItem">
        <img :src="currentKillItem.image" :alt="currentKillItem.name" class="item-img" />
        <div class="item-details">
          <div class="item-name">{{ currentKillItem.name }}</div>
          <div class="item-price">
            <span class="kill-price">¥{{ currentKillItem.killPrice }}</span>
            <span class="original-price">¥{{ currentKillItem.price }}</span>
          </div>
        </div>
      </div>
      
      <div class="address-list">
        <div class="address-title">选择收货地址：</div>
        <el-radio-group v-model="selectedAddress" class="address-group">
          <el-radio
            v-for="addr in addressList"
            :key="addr.id"
            :label="addr.id"
            class="address-item"
          >
            <div class="address-content">
              <div class="address-header">
                <span class="receiver">{{ addr.receiver }}</span>
                <span class="phone">{{ addr.phone }}</span>
                <el-tag v-if="addr.isDefault === 1" type="danger" size="small">默认</el-tag>
              </div>
              <div class="address-detail">
                {{ addr.province }} {{ addr.city }} {{ addr.district }} {{ addr.detailAddress }}
              </div>
            </div>
          </el-radio>
        </el-radio-group>
      </div>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelKill">取消</el-button>
        <el-button 
          type="danger" 
          @click="confirmKill"
          :loading="currentKillItem && addingToCart[currentKillItem.id]"
        >
          确认抢购
        </el-button>
      </span>
    </template>
  </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getKillItemsService, addKillOrderService, type KillItem } from '@/api/kill'
import { getAddressListService } from '@/api/address'

const router = useRouter()
const killItems = ref<KillItem[]>([])
const loading = ref(false)
const timeLeft = ref('')
const addingToCart = ref<Record<number, boolean>>({})

// 地址选择对话框
const showAddressDialog = ref(false)
const addressList = ref<any[]>([])
const selectedAddress = ref<number | null>(null)
const currentKillItem = ref<KillItem | null>(null)

// 倒计时定时器
let timer: number | null = null

// 计算倒计时
const calculateTimeLeft = () => {
  const now = new Date()
  const endTime = new Date()
  endTime.setHours(23, 59, 59, 999)
  
  const diff = endTime.getTime() - now.getTime()
  
  if (diff <= 0) {
    timeLeft.value = '已结束'
    return
  }
  
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
  const seconds = Math.floor((diff % (1000 * 60)) / 1000)
  
  timeLeft.value = `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`
}

// 获取秒杀商品列表
const fetchKillItems = async () => {
  loading.value = true
  try {
    const response = await getKillItemsService()
    if (response.code === 0 && response.data) {
      killItems.value = response.data
    }
  } catch (error) {
    console.error('获取秒杀商品失败:', error)
    ElMessage.error('获取秒杀商品失败')
  } finally {
    loading.value = false
  }
}

// 获取地址列表
const fetchAddressList = async () => {
  try {
    const response = await getAddressListService()
    if (response.code === 0 && response.data) {
      addressList.value = response.data
      // 默认选择默认地址
      const defaultAddr = addressList.value.find(addr => addr.isDefault === 1)
      if (defaultAddr) {
        selectedAddress.value = defaultAddr.id
      } else if (addressList.value.length > 0) {
        selectedAddress.value = addressList.value[0].id
      }
    }
  } catch (error) {
    console.error('获取地址列表失败:', error)
  }
}

// 点击立即抢购
const handleAddToCart = async (item: KillItem) => {
  currentKillItem.value = item
  
  // 获取地址列表
  await fetchAddressList()
  
  if (addressList.value.length === 0) {
    ElMessageBox.confirm('您还没有收货地址，是否前往添加？', '提示', {
      confirmButtonText: '去添加',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      router.push('/account/address')
    }).catch(() => {})
    return
  }
  
  // 显示地址选择对话框
  showAddressDialog.value = true
}

// 确认抢购
const confirmKill = async () => {
  if (!selectedAddress.value || !currentKillItem.value) {
    ElMessage.warning('请选择收货地址')
    return
  }
  
  const item = currentKillItem.value
  addingToCart.value[item.id] = true
  
  try {
    // 创建订单
    const orderResponse = await addKillOrderService(
      item.id,
      1,
      selectedAddress.value,
      item.spec
    )
    
    if (orderResponse.code !== 0) {
      ElMessage.error(orderResponse.message || '下单失败')
      return
    }
    
    const orderData = orderResponse.data
    if (!orderData || !orderData.orderId) {
      ElMessage.error('订单信息获取失败')
      return
    }
    
    // 关闭对话框
    showAddressDialog.value = false
    
    // 跳转到支付页面
    ElMessage.success('订单创建成功，请尽快完成支付')
    router.push({
      path: '/payment',
      query: {
        orderId: orderData.orderId,
        amount: orderData.amount
      }
    })
  } catch (error: any) {
    console.error('下单失败:', error)
    ElMessage.error(error.response?.data?.message || '下单失败，请重试')
  } finally {
    addingToCart.value[item.id] = false
  }
}

// 取消抢购
const cancelKill = () => {
  showAddressDialog.value = false
  currentKillItem.value = null
}

// 跳转到商品详情
const goToDetail = (id: number) => {
  router.push(`/product/${id}`)
}

onMounted(() => {
  fetchKillItems()
  calculateTimeLeft()
  timer = window.setInterval(calculateTimeLeft, 1000)
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style lang="scss" scoped>
.kill-section-wrapper {
  width: 100%;
  max-width: 75rem;
  margin: 0 auto;
  padding: 0 0.9375rem;
}

.kill-section {
  background: linear-gradient(135deg, #ff6b6b 0%, #ff8787 100%);
  border-radius: 8px;
  padding: 16px;
  margin: 20px auto;
  max-width: 100%;
  box-shadow: 0 4px 12px rgba(255, 107, 107, 0.3);
  
  .kill-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    
    .kill-title {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .fire-icon {
        font-size: 24px;
        animation: pulse 1.5s ease-in-out infinite;
      }
      
      .title-text {
        font-size: 20px;
        font-weight: bold;
        color: #fff;
        text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
      }
    }
    
    .kill-timer {
      display: flex;
      align-items: center;
      gap: 8px;
      background: rgba(255, 255, 255, 0.2);
      padding: 6px 12px;
      border-radius: 20px;
      
      .timer-label {
        color: #fff;
        font-size: 14px;
      }
      
      .timer-value {
        color: #fff;
        font-size: 16px;
        font-weight: bold;
        font-family: 'Courier New', monospace;
      }
    }
  }
  
  .kill-content {
    background: #fff;
    border-radius: 8px;
    padding: 16px;
    min-height: 200px;
    
    .kill-items {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
      gap: 16px;
      
      .kill-item {
        background: #fff;
        border: 1px solid #f0f0f0;
        border-radius: 8px;
        padding: 12px;
        cursor: pointer;
        transition: all 0.3s ease;
        
        &:hover {
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
          transform: translateY(-2px);
        }
        
        .item-image {
          position: relative;
          width: 100%;
          padding-bottom: 100%;
          margin-bottom: 12px;
          overflow: hidden;
          border-radius: 6px;
          
          img {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
          
          .kill-badge {
            position: absolute;
            top: 8px;
            left: 8px;
            background: #ff4d4f;
            color: #fff;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: bold;
          }
        }
        
        .item-info {
          .item-name {
            font-size: 14px;
            color: #333;
            margin-bottom: 8px;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            line-height: 1.4;
            height: 2.8em;
          }
          
          .item-price {
            display: flex;
            align-items: baseline;
            gap: 8px;
            margin-bottom: 8px;
            
            .kill-price {
              font-size: 20px;
              font-weight: bold;
              color: #ff4d4f;
            }
            
            .original-price {
              font-size: 14px;
              color: #999;
              text-decoration: line-through;
            }
          }
          
          .item-stock {
            font-size: 12px;
            color: #ff4d4f;
            margin-bottom: 12px;
          }
          
          .add-cart-btn {
            width: 100%;
            background: linear-gradient(135deg, #ff6b6b 0%, #ff8787 100%);
            border: none;
            font-weight: bold;
            
            &:hover {
              background: linear-gradient(135deg, #ff5252 0%, #ff6b6b 100%);
            }
          }
        }
      }
    }
    
    .empty-state {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 200px;
      color: #999;
      font-size: 14px;
    }
  }
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.2);
  }
}

@media (max-width: 768px) {
  .kill-section {
    .kill-content {
      .kill-items {
        grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
        gap: 12px;
      }
    }
  }
}

// 地址选择对话框样式
.address-dialog {
  .kill-item-info {
    display: flex;
    gap: 12px;
    padding: 16px;
    background: #f5f5f5;
    border-radius: 8px;
    margin-bottom: 20px;
    
    .item-img {
      width: 80px;
      height: 80px;
      object-fit: cover;
      border-radius: 6px;
    }
    
    .item-details {
      flex: 1;
      
      .item-name {
        font-size: 14px;
        color: #333;
        margin-bottom: 8px;
        line-height: 1.4;
      }
      
      .item-price {
        display: flex;
        align-items: baseline;
        gap: 8px;
        
        .kill-price {
          font-size: 20px;
          font-weight: bold;
          color: #ff4d4f;
        }
        
        .original-price {
          font-size: 14px;
          color: #999;
          text-decoration: line-through;
        }
      }
    }
  }
  
  .address-list {
    .address-title {
      font-size: 14px;
      font-weight: bold;
      color: #333;
      margin-bottom: 12px;
    }
    
    .address-group {
      width: 100%;
      
      .address-item {
        width: 100%;
        margin-bottom: 12px;
        padding: 12px;
        border: 1px solid #e0e0e0;
        border-radius: 6px;
        transition: all 0.3s ease;
        
        &:hover {
          border-color: #ff4d4f;
          background: #fff8f8;
        }
        
        :deep(.el-radio__label) {
          width: 100%;
        }
        
        .address-content {
          width: 100%;
          
          .address-header {
            display: flex;
            align-items: center;
            gap: 12px;
            margin-bottom: 8px;
            
            .receiver {
              font-size: 14px;
              font-weight: bold;
              color: #333;
            }
            
            .phone {
              font-size: 14px;
              color: #666;
            }
          }
          
          .address-detail {
            font-size: 13px;
            color: #666;
            line-height: 1.5;
          }
        }
      }
      
      :deep(.el-radio.is-checked) {
        .address-item {
          border-color: #ff4d4f;
          background: #fff8f8;
        }
      }
    }
  }
}
</style>
